package com.yungu.swift.monitor.license;

import java.net.*;
import java.util.Enumeration;

/**
 * @author : cuixiuyin
 * @date : 2019/9/12
 */
public class IpAndMac {

    /**
     * 获得机器 Mac 地址
     *
     * @throws SocketException
     */
    public static void getLocalMac() throws SocketException, UnknownHostException {
        //获取网卡，获取地址
        byte[] mac = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            //字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                sb.append("0" + str);
            } else {
                sb.append(str);
            }
        }
        System.out.println("MAC:" + sb.toString().toUpperCase());
    }


    /**
     * 获得内网IP
     *
     * @return
     * @throws UnknownHostException
     */
    public static String getIntranetIp() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }


    /**
     * 获得公网IP，如果没设置公网IP，就返回内网IP
     */
    public static String getInternetIp() throws UnknownHostException, SocketException {
        String intranetIp = getIntranetIp();
        Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        while (networks.hasMoreElements()) {
            Enumeration<InetAddress> addrs = networks.nextElement().getInetAddresses();
            while (addrs.hasMoreElements()) {
                InetAddress ip = addrs.nextElement();
                if (ip != null && ip instanceof Inet4Address && ip.isSiteLocalAddress()
                        && !ip.getHostAddress().equals(intranetIp)) {
                    return ip.getHostAddress();
                }
            }
        }
        // 如果没有外网IP，就返回内网IP
        return intranetIp;
    }
}
